﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.Runtime.Session;
using Abp.UI;
using Basefr.App;
using Basefr.App.Helper;
using Basefr.Consts;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Paas.App.Interface.Menu;
using Paas.App.Interface.Menu.Dtos;
using Paas.App.Interface.Meta;
using Paas.App.Interface.Meta.Dtos;
using Paas.App.Interface.Meta.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaPages.Entities;
using Paas.Core.MetaViews.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Paas.App.Meta
{
    [Route("meta-menu")]

    [AbpAuthorize()]
    public class MenuAppService : AppService, IMenuAppService
    {
        private readonly string pageLayout;
        private readonly IMainRepository<Application> _applicationRepo;
        private readonly IMainRepository<MetaPage,Guid> _metaPageRepo;


        public MenuAppService(IConfiguration configuration, IMainRepository<Application> applicationRepo, IMainRepository<MetaPage,Guid> metaPageRepo)
        {
            pageLayout=configuration["Others:PageLayout"];
            _applicationRepo = applicationRepo;
            _metaPageRepo = metaPageRepo;
        }


        #region 查
        [HttpGet(nameof(GetMenuList))]
        public async Task<List<MenuDto>> GetMenuList()
        {
            //搜索所有已发布的应用
            Expression<Func<Application, bool>> predicate = p => p.CurrentStatus ==MetaStatus.Released;

            var result = await _applicationRepo.GetAllListAsync(predicate);
            var menuList = new List<MenuDto>();
            if (result!=null&&result.Count > 0)
            {
                foreach (var item in result)
                {
                    //获取页面相关配置作为应用相应子页
                    var pages = _metaPageRepo.GetAllList(p => p.ApplicationId==item.Id);
                    var children = new List<MenuDto>();
                    if (pages!=null)
                    {
                        foreach (var page in pages)
                        {
                            children.Add(new MenuDto()
                            {
                                Text=page.Label,
                                Link=$"/{pageLayout}/{page.Id}"
                            });
                        }
                    }
                    //构造menu的参数
                    menuList.Add(new MenuDto()
                    {
                        Text=item.Label,
                        //Acl=new Acl() { Ability=new List<string>() { item.Name } },
                        Acl=new Acl() { Ability=new List<string>() { "Notification" } },
                        Icon=new MenuIcon() { Type="icon", Value="menu" },
                        Children=children,
                    });
                }
            }
            return menuList;
        }

        #endregion

    }
}
